<template>
  <div class="flex mt-6">
    <div class="flex flex-wrap items-center">
      <img
        class="w-12 h-12 rounded object-contain"
        v-if="imageAttached"
        :src="content[type].url"
        :title="`${label}`"
      />
      <button
        v-if="!imageAttached"
        class="p-3 rounded bg-gray-700 cursor-pointer hover:bg-gray-600 focus:bg-gray-600 transition-colors duration-200 focus:outline-none"
        @click="attachMedia()"
        :class="
          dragOver ? 'bg-gray-900 outline-white' : 'bg-gray-700 border-none'
        "
        :aria-label="label"
        @drop.prevent="fileLoaded($event, true)"
        @dragleave.prevent.self="dragOver = false"
        @dragover.prevent.self="dragOver = true"
      >
        <input
          ref="import"
          type="file"
          :accept="acceptedTypes"
          v-show="false"
          @change="fileLoaded($event, false)"
          @click="$event.target.files = null"
        />
        <div
          class="w-6 h-6 pointer-events-none"
          v-html="require(`~/assets/icons/add.svg?include`)"
        ></div>
      </button>
      <p v-if="!imageAttached" class="ml-3 leading-none">
        {{ label
        }}<span class="text-sm text-gray-400"><br />{{ description }}</span>
      </p>
      <button
        v-else
        class="p-1 m-2 shrink-0 focus:outline-none rounded hover:bg-gray-700 focus:bg-gray-700 transition-colors duration-200"
        @click="removeImage()"
        aria-label="Remove image"
        title="Remove image"
      >
        <div
          class="w-6 h-6"
          v-html="require(`~/assets/icons/x.svg?include`)"
        ></div>
      </button>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { uploadConfig } from '~/services/api.config'

export default {
  name: 'MediaUpload',
  props: {
    content: {
      type: Object,
      required: true
    },
    type: {
      type: String,
      required: true
    },
    label: {
      type: String,
      required: true
    },
    description: {
      type: String,
      default: ''
    },
    showAlert: {
      type: Function,
      required: true
    }
  },
  data() {
    return {
      dragOver: false
    }
  },
  computed: {
    imageAttached() {
      return this.content[this.type] && this.content[this.type].url
    },
    acceptedTypes() {
      return 'image/jpeg,image/png,image/gif,image/webp'
    }
  },
  methods: {
    attachMedia() {
      this.$refs.import.click()
    },
    async fileLoaded(e, dropped) {
      if (
        (dropped && e.dataTransfer.files.length) ||
        (!dropped && e.target.files.length)
      ) {
        let file = dropped ? e.dataTransfer.files[0] : e.target.files[0]
        this.dragOver = false
        
        if (file) {
          const mimetype = file.type
          if (this.isImageType(mimetype)) {
            await this.imageLoaded(file, mimetype)
          } else {
            this.showAlert('只支持 jpeg, png, gif 和 webp 格式的图片文件')
          }
        }
      } else {
        this.dragOver = false
      }
    },
    isImageType(mimetype) {
      return ['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(mimetype)
    },
    async imageLoaded(file, mime) {
      try {
        // 创建 FormData 对象
        const formData = new FormData()
        formData.append('file', file)
        
        // 上传文件到接口
        const response = await axios.post(
          uploadConfig.uploadUrl,
          formData,
          {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }
        )
        
        // 检查响应
        if (response.data && response.data.code === 0) {
          const uploadedUrl = response.data.data.url
          const ext = file.name.split('.').pop()
          
          // 直接设置图片数据，不进行切割
          this.$set(this.content, this.type, {
            url: uploadedUrl,
            blob: file,
            ext: ext,
            mime: mime,
            resized: file // 使用原文件作为resized
          })
        } else {
          this.showAlert('文件上传失败，请重试')
        }
      } catch (error) {
        console.error('Upload error:', error)
        this.showAlert('文件上传失败，请重试')
      }
    },
    removeImage() {
      this.$set(this.content, this.type, {
        url: null,
        blob: null,
        ext: null,
        mime: null,
        resized: null
      })
    }
  }
}
</script>
